package com.baymax.custom.context;

import lombok.experimental.UtilityClass;
import org.springframework.util.StopWatch;

import java.util.Map;
import java.util.Optional;

/**
 * StopWatchContext
 *
 * @author hujiabin wrote in 2024/1/20 16:37
 */
@UtilityClass
public class StopWatchContext {

    /**
     * key是stopWatchId value是对应的StopWatch对象
     */
    public static final ThreadLocal<Map<String, StopWatch>> STOP_WATCH_THREAD_LOCAL = new ThreadLocal<>();


    /**
     * 是否已经开启了注解
     *
     * @return 是否
     */
    public static boolean isOpenExecutionTimeStatistics() {
        return Optional.ofNullable(STOP_WATCH_THREAD_LOCAL.get()).isPresent();
    }

    /**
     * 是否有StopWatch
     *
     * @return 是否
     */
    public static boolean hasStopWatch() {
        return !STOP_WATCH_THREAD_LOCAL.get().isEmpty();
    }

    /**
     * 开启耗时统计
     *
     * @param map map
     */
    public static void openExecutionTimeStatistics(Map<String, StopWatch> map) {
        STOP_WATCH_THREAD_LOCAL.set(map);
    }

    /**
     * 获取所有StopWatch
     *
     * @return map
     */
    public static Map<String, StopWatch> getAllStopWatch() {
        return STOP_WATCH_THREAD_LOCAL.get();
    }

    /**
     * 关闭耗时统计
     */
    public static void closeExecutionTimeStatistics() {
        STOP_WATCH_THREAD_LOCAL.remove();
    }
}
